package com.ecb.business.service.impl;

import com.ecb.business.dto.organization.OrganizationDTO;
import com.ecb.business.dto.organization.QueryOrganizationDTO;
import com.ecb.business.exception.BusinessException;
import com.ecb.business.po.ChainOrganizationPO;
import com.ecb.business.repository.ChainOrgRelDao;
import com.ecb.business.service.OrganizationManageService;
import com.ecb.business.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class OrganizationManageServiceImpl implements OrganizationManageService {

    @Autowired
    ChainOrgRelDao chainOrgRelDao;
    @Override
    public List<OrganizationDTO> getAllOrg(QueryOrganizationDTO queryDTO) {
        List<ChainOrganizationPO> allByOrgIdLikeOrOrgNameLikeAndStatusEquals = chainOrgRelDao.findAllByOrgIdLikeOrOrgNameLikeAndStatusEquals(queryDTO.getOrgId(), queryDTO.getOrgName(), 1);
        List<OrganizationDTO> organizationDTOS = JsonUtils.beanToArray(allByOrgIdLikeOrOrgNameLikeAndStatusEquals, OrganizationDTO.class);
        return organizationDTOS;
    }

    @Override
    public boolean addOrg(OrganizationDTO addDTO) {
        ChainOrganizationPO organizationPO = new ChainOrganizationPO();
        organizationPO.setStatus(1);
        organizationPO.setOrgId(addDTO.getOrgId());
        organizationPO.setOrgName(addDTO.getOrgName());
        organizationPO.setCreateTime(new Date());
        organizationPO.setModifyTime(new Date());
        chainOrgRelDao.save(organizationPO);
        return true;
    }

    @Override
    public boolean updateOrg(OrganizationDTO organizationDTO) {
        Optional<ChainOrganizationPO> byId = chainOrgRelDao.findById(organizationDTO.getId());
        if (!byId.isPresent()){
            throw new BusinessException(500, "组织不存在");
        }
        ChainOrganizationPO organizationPO = byId.get();
        organizationPO.setOrgId(organizationDTO.getOrgId());
        organizationPO.setOrgName(organizationDTO.getOrgName());
        chainOrgRelDao.save(organizationPO);
        return true;
    }

    @Override
    public boolean deleteOrg(OrganizationDTO organizationDTO) {
        Optional<ChainOrganizationPO> byId = chainOrgRelDao.findById(organizationDTO.getId());
        if (!byId.isPresent()){
            throw new BusinessException(500, "组织不存在");
        }
        ChainOrganizationPO organizationPO = byId.get();
        organizationPO.setStatus(9);
        organizationPO.setModifyTime(new Date());
        chainOrgRelDao.save(organizationPO);
        return true;
    }
}
